import * as auth from './auth.js'
import * as ResponseStatus from '@/common/response-status.js'
import moment from 'moment'; //导入模块
// export const BASE_URL = 'http://ceshi.zgwlkj.cn:10081'
// export const FRONT_BASE_URL = 'http://ceshi.zgwlkj.cn:10081/'
// export const DOCUMENT_BASE_URL = 'http://ceshi.zgwlkj.cn:10081'
// export const SOCKET_URL = 'ws://ceshi.zgwlkj.cn:10081'

// export const BASE_URL = 'http://192.168.2.65:8080'
// export const FRONT_BASE_URL = 'http://192.168.2.65:8080/'
// export const DOCUMENT_BASE_URL = 'http://192.168.2.65:8080'
// export const SOCKET_URL = 'ws://192.168.2.65:8080'

// export const BASE_URL = 'http://192.168.3.42:8080'
// export const FRONT_BASE_URL = 'http://192.168.3.42:8080/'
// export const DOCUMENT_BASE_URL = 'http://192.168.3.42:8080'
// export const SOCKET_URL = 'ws://192.168.3.42:8080'

export const BASE_URL = 'https://yunzhuan.zgwlkj.cn/api-admin'
export const FRONT_BASE_URL = 'https://yunzhuan.zgwlkj.cn/api-admin/'
export const DOCUMENT_BASE_URL = 'https://yunzhuan.zgwlkj.cn/api-admin'
export const SOCKET_URL = 'wss://yunzhuan.zgwlkj.cn/api-admin'

export const SHARE_TITLE = '云赚'
export const USER_TOKEN_KEY = 'userToken'
export const USER_OPENID = 'openid'
export const SHARE_CODE = 'shareCode'
export const MY_SHARE_CODE = 'myShareCode'
export const USER_INFO = 'userInfo'
export const USER_ID = 'userId'
export const USER_ROLES = 'userRoles'
export const USER_PHONE = 'userPhone'
export const USER_NICKNAME = 'userNickname'
export const USER_HEADICON = 'userHeadicon'
export const USER_GENDER = 'userGender'
export const HAS_USER_INFO = 'hasUserInfo' //缓存登录状态
export const USER_BIRTHDAY = 'birthday'
export const USER_LOCATION = 'userLocation'
export const DEFAULT_HEADICON = '/static/missing-face.png'
export const SHARE_CODE_PAGE_IMG = '/static/share/share.jpg'
export const REFRESH_CART = 'refreshCart'
export const REFRESH_PRODUCT = 'refreshProduct'
export const REFRESH_ORDER = 'refreshOrder'
export const MALL_DISTRIBUTOR_FLAG = 'mallDistributorFlag'
export const PHONE_NUMBER = "400-9155-725" //全局客服电话
export const PROVINCE = "province" //城市信息缓存
export const AUTH = "authorization" //拼多多授权缓存
export const COUNT = "count" //记录接口token失效次数
export const APPID = 'APPid-zg'
export const APP_VERSION = "Appversion"
export const UUID = "uuid" //设备ID
export const ADPID = "adpid" //激励视频广告位id
/**
 * 判断是否为空（null, '', undefined）
 */
export const isEmpty = (data) => {
	return !data
}

/**
 * 判断是否不为空（null, '', undefined）
 */
export const isNotEmpty = (data) => {
	return !isEmpty(data)
}

/**
 * 清除表单
 */
export const clearForm = (form) => {
	for (let key in form) {
		form[key] = null
	}
}
/**
 * token失效
 */
export const invalidToken = () => {
	uni.removeStorageSync(USER_TOKEN_KEY)
	uni.removeStorageSync(HAS_USER_INFO)
	// if(!uni.getStorageSync(COUNT)){
	// 	showInfoToast('登录已失效，请重新登录')
	// }
}
//token失效跳转登录页
export const toLogin = () => {
	console.log("token失效跳转到登陆页")
	uni.setStorageSync(COUNT, 0)
	if (!uni.getStorageSync(COUNT)) {
		uni.setStorageSync(COUNT, 1)
		uni.reLaunch({
			url: '/pages/login/login'
		})
	}
}
/**
 * 网络异常
 */
export const networkError = () => {
	showInfoToast('网络有问题哦~')
}
/**
 * 显示提示信息
 */
export const showInfoToast = (title) => {
	uni.showToast({
		title: title,
		icon: 'none',
		duration: 2000
	})
}
/**
 * 显示成功的信息
 */
export const showSuccessToast = (title) => {
	uni.showToast({
		title: title,
		duration: 2000
	})
}
/**
 * 获取日历日期
 */
export const getCalendarDate = (date) => {
	if (typeof date !== 'object') {
		date = date.replace(/-/g, '/')
	}
	let dd = new Date(date);
	let y = dd.getFullYear();
	let m = dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1
	let d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate()
	return y + '-' + m + '-' + d
}
/**
 * 格式化日历日期
 */
export const formatCalendarDate = (date) => {
	if (typeof date !== 'object') {
		date = date.replace(/-/g, '/')
	}
	let dd = new Date(date);
	let y = dd.getFullYear();
	let m = dd.getMonth() + 1
	let d = dd.getDate()
	let w = dd.getDay()
	let week = '星期'
	switch (w) {
		case 0:
			week = week + '日';
			break;
		case 1:
			week = week + '一';
			break;
		case 2:
			week = week + '二';
			break;
		case 3:
			week = week + '三';
			break;
		case 4:
			week = week + '四';
			break;
		case 5:
			week = week + '五';
			break;
		case 6:
			week = week + '六';
			break;
		default:
			break;
	}
	return y + '-' + m + '-' + d + ' ' + week
}
/**
 * 获取时间
 */
export const getDate = (type) => {
	const date = new Date();

	let year = date.getFullYear();
	let month = date.getMonth() + 1;
	let day = date.getDate();

	if (type === 'start') {
		year = year - 60;
	} else if (type === 'end') {
		year = year + 2;
	}
	month = month > 9 ? month : '0' + month;
	day = day > 9 ? day : '0' + day;

	return `${year}-${month}-${day}`;
}
/**
 * 获取当前时间
 */
export const getCurrentDate = () => {
	let date = new Date()
	let year = date.getFullYear()
	let month = date.getMonth() + 1
	let day = date.getDate()
	month = month > 9 ? month : '0' + month
	day = day > 9 ? day : '0' + day
	return year + '-' + month + '-' + day
}

/**
 * null转成空字符串
 */
export const nullToStr = (data) => {
	for (let x in data) {
		if (data[x] === null) { // 如果是null 把直接内容转为 ''
			data[x] = '';
		} else {
			if (Array.isArray(data[x])) { // 是数组遍历数组 递归继续处理
				data[x] = data[x].map(z => {
					return nullToStr(z);
				});
			}
			if (typeof(data[x]) === 'object') { // 是json 递归继续处理
				data[x] = nullToStr(data[x])
			}
		}
	}
	return data;
}

/**
 * 取指定的日期
 * @param {type} 7：上周开始时间 1：上周结束时间 0：本周开始时间 -6：本周结束时间 -7：下周开始时间 -13：下周结束时间  
 */
export const getAppointWeekDate = (n) => {
	var now = new Date();
	var year = now.getFullYear();
	//因为月份是从0开始的,所以获取这个月的月份数要加1才行
	var month = now.getMonth() + 1;
	var date = now.getDate();
	var day = now.getDay();
	//判断是否为周日,如果不是的话,就让今天的day-1(例如星期二就是2-1)
	if (day !== 0) {
		n = n + (day - 1);
	} else {
		n = n + day;
	}
	if (day) {
		//这个判断是为了解决跨年的问题
		if (month > 1) {
			month = month;
		}
		//这个判断是为了解决跨年的问题,月份是从0开始的
		else {
			year = year - 1;
			month = 12;
		}
	}
	now.setDate(now.getDate() - n);
	year = now.getFullYear();
	month = now.getMonth() + 1;
	date = now.getDate();
	// console.log(n);
	var s = year + "-" + (month < 10 ? ('0' + month) : month) + "-" + (date < 10 ? ('0' + date) : date);
	return s;
}

/**
 * 获取本月第一天或最后一天的日期
 * @param type 默认是获取本月第一天的日期，传入1:获取本月最后一天的日期
 */
export const showMonthFirstOrLastDay = (type) => {
	var nowDate = new Date();
	var monthFirstDay = new Date(nowDate.getYear(), nowDate.getMonth() + 1, 1);
	var monthLastDay = new Date(monthFirstDay - 86400000);
	var month = Number(monthFirstDay.getMonth())
	if (month === 0) {
		month = 12
	}
	var day = monthFirstDay.getDate();
	if (1 === type) {
		month = Number(monthLastDay.getMonth()) + 1
		day = Number(monthLastDay.getDate());
	}
	month = month < 10 ? '0' + month : month;
	day = day < 10 ? '0' + day : day;
	return nowDate.getFullYear() + "-" + month + "-" + day;
}

/**
 * 判断是否是真实姓名
 */
export const isRegName = (regName) => {
	var regNameExp = /^[\u4e00-\u9fa5]{2,6}$/;
	return regNameExp.test(regName);
}

/**
 * 获取下月第一天或最后一天的日期
 * @param type 默认是获取下月第一天的日期，传入1:获取下月最后一天的日期
 */
export const showNextMonthFirstOrLastDay = (type) => {
	var now = new Date();
	var year = now.getFullYear();
	var month = now.getMonth() + 1;
	var date = now.getDate();
	// 解决跨年的问题
	if (12 === month) {
		// 当前是12月，则下月是1月
		month = 1;
		year = year + 1;
	} else {
		// 获取下个月的月份
		month = month + 1;
	}
	var monthFirstDay = new Date(year, month, 1);
	var monthLastDay = new Date(year, month, 0);
	var tempMonth = Number(monthFirstDay.getMonth())
	var tempDay = monthFirstDay.getDate();
	if (1 === type) {
		tempMonth = Number(monthLastDay.getMonth()) + 1
		tempDay = Number(monthLastDay.getDate());
	}
	tempMonth = tempMonth < 10 ? '0' + tempMonth : tempMonth;
	tempDay = tempDay < 10 ? '0' + tempDay : tempDay;
	return year + "-" + tempMonth + "-" + tempDay;
}

/**
 * 判断是否是手机号
 */
export const isPhone = (phone) => {
	var phoneExp = /^[1][2,3,4,5,6,7,8,9][0-9]{9}$/;
	return phoneExp.test(phone);
}
/**
 * 页面跳转,保留当前页面
 * @param {Object} url 跳转的url
 * @param {Object} isLogin 是否需要验证登入
 */
export const navTo = (url, isLogin) => {
	if (isLogin) {
		// 需要验证是否有登入,后面完成，暂时不验证
	}
	uni.navigateTo({
		url: url
	})
}
/**
 * 页面跳转，不保留当前页面
 * @param {Object} url 跳转的url
 * @param {Object} isLogin 是否需要验证登入
 */
export const redTo = (url, isLogin) => {
	if (isLogin) {
		// 需要验证是否有登入,后面完成，暂时不验证
	}
	uni.redirectTo({
		url: url
	})
}

/**
 * post请求，application/json
 * @param {*} url 请求url
 * @param {*} data json对象
 * @param {*} headers 如headers: {
                          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
                          'Authorization': 'Bearer ' + getLocalStorageToken()
                        }
                      如果不需要传递headers，则直接使用{}
 * @param {*} token 如传true：需要token，传false：不需要token
 */
export const doPostJson = (url, data, headers, token) => {
	if (token) {
		const userToken = uni.getStorageSync(USER_TOKEN_KEY)
		headers['Authorization'] = userToken
	}
	// headers['App-Auth-appid'] = auth.APPID
	// if (auth.APP_AUTH_ENABLE) {
	// 	headers['App-Auth-reqUrl'] = url
	// 	let timestamp = new Date().getTime()
	// 	let nonceStr = uuid()
	// 	headers['App-Auth-timestamp'] = timestamp
	// 	headers['App-Auth-nonceStr'] = nonceStr
	// 	headers['App-Auth-sign'] = auth.generateSignJson(url, timestamp, nonceStr, data)
	// }
	return new Promise((resolve, reject) => {
		uni.request({
			url: BASE_URL + url,
			method: 'POST',
			data: data,
			header: headers,
			sslVerify: true,
			success: (res) => {
				console.log("请求信息", url)
				if (res.statusCode === ResponseStatus.OK && res.data.code === ResponseStatus
					.OK) {
					resolve(res)
				} else if (res.data.code === ResponseStatus.AUTHENTICATION_TOKEN_ERROR) {
					invalidToken()
					setTimeout(() => {
						toLogin()
					}, 2000)
				} else if (res.data.code === ResponseStatus.ERROR || res.statusCode ===
					ResponseStatus.ERROR) {
					// showInfoToast(res.data.message)
					resolve(res)
					console.log("请求"+url,res)
					if(res.data.message){
						showInfoToast(res.data.message)
					}
				} else {
					resolve(res)
				}
			},
			fail: (error) => {
				reject(error)
			}
		})
	})
}

/**
 * post请求，application/x-www-form-urlencoded
 * @param {*} url 请求url
 * @param {*} data json对象
 * @param {*} headers 如headers: {
                          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
                          'Authorization': 'Bearer ' + getLocalStorageToken()
                        }
                      如果不需要传递headers，则直接使用{}
 * @param {*} token 如传true：需要token，传false：不需要token
 */
export const doPostForm = (url, data, headers, token) => {
	headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
	if (token) {
		const userToken = uni.getStorageSync(USER_TOKEN_KEY)
		headers['Authorization'] = userToken
	}
	// headers['App-Auth-appid'] = auth.APPID
	// if (auth.APP_AUTH_ENABLE) {
	// 	headers['App-Auth-reqUrl'] = url
	// 	let timestamp = new Date().getTime()
	// 	let nonceStr = uuid()
	// 	headers['App-Auth-timestamp'] = timestamp
	// 	headers['App-Auth-nonceStr'] = nonceStr
	// 	headers['App-Auth-sign'] = auth.generateSign(url, timestamp, nonceStr, data)
	// }
	return new Promise((resolve, reject) => {
		uni.request({
			url: BASE_URL + url,
			method: 'POST',
			data: data,
			header: headers,
			sslVerify: true,
			success: (res) => {
				console.log("请求信息", url)
				if (res.data.code === ResponseStatus.OK) {
					resolve(res)
				} else if (res.data.code === ResponseStatus.AUTHENTICATION_TOKEN_ERROR) {
					invalidToken()
					setTimeout(() => {
						toLogin()
					}, 2000)
				} else if (res.data.code === ResponseStatus.ERROR || res.statusCode ===
					ResponseStatus.ERROR) {
					// showInfoToast("服务器繁忙")
					resolve(res)
					console.log("请求"+url,res)
					if(res.data.message){
						showInfoToast(res.data.message)
					}
				} else {
					resolve(res)
				}
			},
			fail: (error) => {
				reject(error)
			}
		})
	})
}


/**
 * get请求
 * @param {*} url 请求url，包含请求参数
 * @param {*} data 请求数据,JSON对象
 * @param {*} headers 如headers: {
                          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
                          'Authorization': 'Bearer ' + getLocalStorageToken()
                        }
                      如果不需要传递headers，则直接使用{}
 * @param {*} token 如传true：需要token，传false：不需要token
 */
export const doGet = (url, data, headers, token) => {
	if (token) {
		const userToken = uni.getStorageSync(USER_TOKEN_KEY)
		headers['Authorization'] = userToken
		console.log("请求ToKen",userToken)
	}
	// headers['App-Auth-appid'] = auth.APPID
	// if (auth.APP_AUTH_ENABLE) {
	// 	headers['App-Auth-reqUrl'] = url
	// 	let timestamp = new Date().getTime()
	// 	let nonceStr = uuid()
	// 	headers['App-Auth-timestamp'] = timestamp
	// 	headers['App-Auth-nonceStr'] = nonceStr
	// 	headers['App-Auth-sign'] = auth.generateSign(url, timestamp, nonceStr, data)
	// }
	return new Promise((resolve, reject) => {
		if(url.indexOf('?')!== -1){
			url+='&getTime='+moment(new Date()).unix()
		}else {
			url+='?getTime='+moment(new Date()).unix()
		}
		uni.request({
			url: BASE_URL + url,
			method: 'GET',
			data: data,
			header: headers,
			sslVerify: true,
			success: (res) => {
				
				if (res.data.code === ResponseStatus.OK) {
					resolve(res)
				} else if (res.data.code === ResponseStatus.AUTHENTICATION_TOKEN_ERROR) {
					invalidToken()
					setTimeout(() => {
						toLogin()
					}, 2000)
				} else if (res.data.code === ResponseStatus.ERROR || res.statusCode ===
					ResponseStatus.ERROR) {
					resolve(res)
					console.log("请求"+url,res)
					if(res.data.message){
						showInfoToast(res.data.message)
					}
				} else {
					resolve(res)
				}
			},
			fail: (error) => {
				reject(error)
			}
		})
	})
}

export const getConfig = (data) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: "https://zgmg.pinshizhineng.com/api-mg/create/js_api/signature",
			method: 'GET',
			data: data,
			sslVerify: false,
			success: (res) => {
				resolve(res)
			},
			fail: (error) => {
				reject(error)
			}
		})
	})

}

// 获取动态咨询
export function getMicInforList(page = 1, rows = 10) {
	return doPostForm(`/micInfor/mationSta/${page}/${rows}`, {}, {}, true)
}

const DynamicConsultationKey = "DynamicConsultation"

//缓存动态咨询
export function saveDynamicConsultation(data) {
	uni.setStorageSync(DynamicConsultationKey, data)
}

export function getDynamicConsultation() {
	return uni.getStorageSync(DynamicConsultationKey)
}

export function addDynamicConsultationPv(id) {
	return doPostForm(`/micInfor/selectArticleTitle/${id}`, {}, {}, true)
}

// 获取订单列表
export function getOrderList(param) {
	return doGet(`/mallOrder/listByUser`, param, {}, true)
}


// 获取用户信息
export function getUserInfo(param) {
	return doGet(`/user/manager/userInfoList`, param, {}, true)
}

// 云豆规则列表
export function getDepositList(param) {
	return doGet(`/user/deposit/getDepositList`, param, {}, true)
}

// 查询提现列表
export function queryUserDeposit(param) {
	return doGet(`/userAmount/queryUserDeposit`, param, {}, true)
}

// 查询是否绑定提现微信
export function isBindWechat(param) {
	return doGet(`/wx/bind/wechat/can`, param, {}, true)
}

// 提现到微信
export function withdrawalWechat(param) {
	return doPostForm(`/wx/withdrawal`, param, {}, true)
}

// 重新绑定提现微信
export function wxBingWithdrawalSubmit(param) {
	return doPostJson(`/user/wxbingwithdrawal`, param, {}, true)
}

//更新用户在线时长
export function updateUserTime (time){
	return doPostForm(`/report/onlinetime/${time}`, {}, {}, true)
}

//页面访问次数
export function accessPage (type){
	return doPostJson(`/page/accessPage`, {type:type}, {}, true)
}

/**
 * 时间转化，将时间转化为几天前的格式
 * @param {dateTimeStamp}  dateTimeStamp是一个时间毫秒，注意时间戳是秒的形式，在这个毫秒的基础上除以1000，就是十位数的时间戳。13位数的都是时间毫秒。
 */
export const timeAgo = (dateTimeStamp) => {
	var minute = 1000 * 60; //把分，时，天，周，半个月，一个月用毫秒表示
	var hour = minute * 60;
	var day = hour * 24;
	var week = day * 7;
	var halfamonth = day * 15;
	var month = day * 30;
	var now = new Date().getTime(); //获取当前时间毫秒
	console.log(now)
	var diffValue = now - dateTimeStamp; //时间差

	if (diffValue < 0) {
		return;
	}
	var minC = diffValue / minute; //计算时间差的分，时，天，周，月
	var hourC = diffValue / hour;
	var dayC = diffValue / day;
	var weekC = diffValue / week;
	var monthC = diffValue / month;
	var result;
	// if(monthC >= 1 && monthC <= 3){
	//     result = " " + parseInt(monthC) + "月前"
	// }else if(weekC >= 1 && weekC <= 3){
	//     result = " " + parseInt(weekC) + "周前"
	// }else 

	if (dayC >= 1 && dayC <= 2) {
		result = " " + parseInt(dayC) + "天前"
	} else if (hourC >= 1 && hourC <= 23) {
		result = " " + parseInt(hourC) + "小时前"
	} else if (minC >= 1 && minC <= 59) {
		result = " " + parseInt(minC) + "分钟前"
	} else if (diffValue >= 0 && diffValue <= minute) {
		result = "刚刚"
	} else {
		var datetime = new Date();
		datetime.setTime(dateTimeStamp);
		var Nyear = datetime.getFullYear();
		var Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
		var Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
		var Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
		var Nminute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
		var Nsecond = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
		result = Nyear + "-" + Nmonth + "-" + Ndate + " " + Nhour + ":" + Nminute
	}
	return result;
}

export const uuid = () => {
	let s = []
	let hexDigits = "0123456789abcdef"
	for (let i = 0; i < 36; i++) {
		s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
	}
	s[14] = "4" // bits 12-15 of the time_hi_and_version field to 0010
	s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
	s[8] = s[13] = s[18] = s[23] = "-"
	let uuid = s.join("")
	return uuid
}

/**
 * 把url修改为指定后缀的url，如abc.png->abc_400x400.png
 */
export const modifyUrl = (jsonObj, paramName, suffix) => {
	let url = jsonObj[paramName]
	let idx = url.lastIndexOf('.')
	let filename = url.substring(0, idx)
	let fileExt = url.substring(idx + 1)
	jsonObj[paramName] = filename + '_' + suffix + '.' + fileExt
}

/**
 * 图片压缩大小转换，将图片替换为指定的压缩大小
 * @param {JsonData,parameterName,ImgconfigName} 
 * jsonData：要转换的数据json对象
 * parameterName：要转换的参数名称 （图片url参数名）
 * imgconfigName: 转换成指定的压缩配置
 */
export const conversionImg = (jsonData, paramName, imgConfigName) => {
	let sysConfigQuery = {
		name: 'img_compression_config'
	}
	doPostJson('/sys-config/any/pager-cond', sysConfigQuery, {}, true).then(res => {
		let configJson = JSON.parse(res.data.data.rows[0].value)
		modifyUrl(jsonData, paramName, configJson[imgConfigName])
	}).catch(err => {
		console.log(err)
	})
}

/**
 * 图片压缩大小转换，将返回值图片数组替换为指定的压缩大小
 * @param {JsonData,parameterName,ImgconfigName} 
 * jsonData：要转换的数据json对象(数组集合)
 * parameterName：要转换的参数名称 （图片url参数名）
 * imgconfigName: 转换成指定的压缩配置
 */
export const conversionImgList = (jsonDataList, paramName, imgConfigName) => {
	let sysConfigQuery = {
		name: 'img_compression_config'
	}
	doPostJson('/sys-config/any/pager-cond', sysConfigQuery, {}, true).then(res => {
		let configJson = JSON.parse(res.data.data.rows[0].value)
		let suffix = configJson[imgConfigName]
		jsonDataList.forEach(jsonData => {
			modifyUrl(jsonData, paramName, suffix)
		})
	}).catch(err => {
		console.log(err)
	})
}

export const pictureProcessing = (url) => {
	if (url && url.indexOf('http') < 0) {
		url = FRONT_BASE_URL + url
	}
	return url
}

export const appOpenUrl = (url) => {
	// #ifdef APP-PLUS
	plus.runtime.openURL(encodeURI(_url));
	// #endif
}

export const jsGetAge = (strBirthday) => {
	var returnAge;
	var strBirthdayArr = strBirthday[0].split("-");
	var birthYear = strBirthdayArr[0];
	var birthMonth = strBirthdayArr[1];
	var birthDay = strBirthdayArr[2];

	var d = new Date();
	var nowYear = d.getFullYear();
	var nowMonth = d.getMonth() + 1;
	var nowDay = d.getDate();

	if (nowYear == birthYear) {
		returnAge = 0; //同年 则为0岁
	} else {
		var ageDiff = nowYear - birthYear; //年之差
		if (ageDiff > 0) {
			if (nowMonth == birthMonth) {
				var dayDiff = nowDay - birthDay; //日之差
				if (dayDiff < 0) {
					returnAge = ageDiff - 1;
				} else {
					returnAge = ageDiff;
				}
			} else {
				var monthDiff = nowMonth - birthMonth; //月之差
				if (monthDiff < 0) {
					returnAge = ageDiff - 1;
				} else {
					returnAge = ageDiff;
				}
			}
		} else {
			returnAge = -1; //返回-1 表示出生日期输入错误 晚于今天
		}
	}
	return returnAge; //返回周岁年龄
}

export const openTB = (link) => {
	let openUrl = "https:" + link;
	// 因为 url 一般是从其它地方获取的，所以这里要将 http 和 https 删去
	// 也可以直接输入 https:// 之后的内容，则不需要此步判断，直接调用 plus.runtime.openURL
	if (openUrl.substr(0, 5) === 'https') {
		openUrl = `taobao://${openUrl.substr(8)}`;
	} else if (openUrl.substr(0, 4) === 'http') {
		openUrl = `taobao://${openUrl.substr(7)}`;
	}
	if (uni.getSystemInfoSync().platform == 'ios') {
		openUrl = openUrl.split('//')[1]
		plus.runtime.openURL('taobao://' + openUrl, function(res) {
			// showModal('你还未下载淘宝，是否立即下载安装？',"itms-apps://itunes.apple.com/cn/app/tao-bao-sui-shi-sui-xiang/id387682726?mt=8")
			uni.navigateTo({
				url:`/pages/common/common?weburl=https:${link}`
			})
		}, 'taobao://');
	} else {
		plus.runtime.openURL(openUrl, function(res) {
			// showModal('你还未下载淘宝，是否立即下载安装？', "market://details?id=com.taobao.taobao")
			uni.navigateTo({
				url:`/pages/common/common?weburl=https:${link}`
			})
		});
	}

}

export const showModal = (content, openUrl) => {
	uni.showModal({
		title: '提示',
		content: content,
		cancelText: "否",
		confirmText: "立即安装",
		success: function(res) {
			if (res.confirm) {
				plus.runtime.openURL(openUrl);
			}
		}
	});
}

export const openPDD = (urlData) => {
	let openUrl = urlData.schemaUrl
	if (uni.getSystemInfoSync().platform == 'ios') {
		plus.runtime.openURL(openUrl, function(res) {
			console.log(res)
			// showModal('你还未下载拼多多，是否立即下载安装？', "itms-apps://itunes.apple.com/cn/app/上海寻梦信息技术有限公司/id1044283058")
			uni.navigateTo({
				url:`/pages/common/common?weburl=${urlData.mobileShortUrl}`
			})
		}, 'pinduoduo://');
	} else {
		plus.runtime.openURL(openUrl, function(res) {
			console.log(res)
			// showModal('你还未下载拼多多，是否立即下载安装？', "market://details?id=com.xunmeng.pinduoduo")
			uni.navigateTo({
				url:`/pages/common/common?weburl=${urlData.mobileShortUrl}`
			})
		});
	}

}
//手机号码处理
export const noPassByMobile = (phone) => {
	if (null != phone && phone != undefined) {
		var pat = /(\d{3})\d*(\d{4})/;
		return phone.replace(pat, '$1****$2');
	} else {
		return "";
	}
}
//获取当前年月日时分秒
export const getTime = (time) => {
	let date = new Date();
	if(time){
		date = new Date(time);
	}
	var year = date.getFullYear(),
		month = date.getMonth() + 1,
		day = date.getDate(),
		hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
		minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
		second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
	month >= 1 && month <= 9 ? (month = "0" + month) : "";
	day >= 0 && day <= 9 ? (day = "0" + day) : "";
	// var timer = year + '-' + month + '-' + day;
	var timer = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
	return timer;
}



